package com.credithc.signature.manager.service;

import com.alibaba.fastjson.JSONObject;
import com.credithc.signature.common.mapper.AdminMapper;
import com.credithc.signature.common.po.AdminRequest;
import com.credithc.signature.common.utils.DateUtil;
import com.credithc.signature.common.utils.HttpClientProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年06⽉12⽇<br/>
 * @version：v1.0.0<br>
 */
@Service
@Slf4j
public class FutureService {

    @Autowired
    AdminMapper adminMapper;


    /**
     * 异步回调业务系统
     *
     * @param requestNo
     * @param token
     * @param callbackUrl
     * @param isSuccess
     * @param resultMsg
     * @param fileId
     * @return
     */
    @Async
    public void callbackBusiness(String requestNo, String token, String callbackUrl, boolean isSuccess, String resultMsg, String fileId) {
        try {
            Date date = new Date();
            JSONObject jsonObj = new JSONObject();
            JSONObject data = new JSONObject();
            data.put("requestNo", requestNo);
            data.put("fileUrl", fileId);
            jsonObj.put("code", isSuccess ? 200 : 100);
            jsonObj.put("msg", resultMsg);
            jsonObj.put("data", data);
            log.info("行政章接口-->－消息－:requestSn={},回调业务系统消息：{}", requestNo, jsonObj.toString());
            String result = HttpClientProxy.post(callbackUrl, jsonObj);

            Example example = new Example(AdminRequest.class);
            Example.Criteria sec = example.createCriteria();
            sec.andEqualTo("requestNo", requestNo);
            sec.andEqualTo("token", token);
            AdminRequest adminRequest = new AdminRequest();
            adminRequest.setUpdateTime(new Date());
            adminRequest.setCallbackStatus(1);
            adminRequest.setResponseMsg(result);
            adminMapper.updateByExampleSelective(adminRequest, example);
            log.info("行政章接口-->－消息－:requestSn={},回调业务系统成功......耗时：{}秒", requestNo, DateUtil.betweenNowSecond(date));
        } catch (Exception e) {
            log.info("行政章接口-->－消息－:requestSn={},回调业务系统失败......", requestNo, e);
            Example example = new Example(AdminRequest.class);
            Example.Criteria sec = example.createCriteria();
            sec.andEqualTo("requestNo", requestNo);
            sec.andEqualTo("token", token);
            AdminRequest adminRequest = new AdminRequest();
            adminRequest.setUpdateTime(new Date());
            adminRequest.setCallbackStatus(2);
            adminRequest.setResponseMsg(e.getMessage());
            adminMapper.updateByExampleSelective(adminRequest, example);
        }
    }
}
